package com.yuanqi.service;

import com.yuanqi.domain.Payment;
import com.yuanqi.repository.PaymentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class PaymentService {
    
    @Autowired
    private PaymentRepository paymentRepository;
    
    public List<Payment> getAllPayments() {
        return paymentRepository.findAll();
    }
    
    public Optional<Payment> getPaymentById(Long id) {
        return paymentRepository.findById(id);
    }
    
    public List<Payment> getPaymentsBySupplier(Long supplierId) {
        return paymentRepository.findBySupplierId(supplierId);
    }
    
    public List<Payment> getPaymentsByDateRange(LocalDate startDate, LocalDate endDate) {
        return paymentRepository.findByPaymentDateBetween(startDate, endDate);
    }
    
    public Payment createPayment(Payment payment) {
        if (paymentRepository.existsByPaymentCode(payment.getPaymentCode())) {
            throw new RuntimeException("付款单号已存在");
        }
        payment.setCreatedAt(LocalDateTime.now());
        return paymentRepository.save(payment);
    }
    
    public Payment updatePayment(Long id, Payment paymentDetails) {
        Payment payment = paymentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("付款记录不存在"));
        
        payment.setSupplierId(paymentDetails.getSupplierId());
        payment.setPaymentDate(paymentDetails.getPaymentDate());
        payment.setAmount(paymentDetails.getAmount());
        payment.setMethod(paymentDetails.getMethod());
        payment.setCurrency(paymentDetails.getCurrency());
        payment.setRemark(paymentDetails.getRemark());
        
        return paymentRepository.save(payment);
    }
    
    public void deletePayment(Long id) {
        paymentRepository.deleteById(id);
    }
    
    public Double getTotalPaymentAmount(LocalDate startDate, LocalDate endDate) {
        return paymentRepository.getTotalPaymentAmount(startDate, endDate);
    }
}


